package com.zgxl.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeUtil {

    private static String dateFormatPattern = "yyyy-MM-dd";
    private static String dateTimeFormatPattern = "yyyy-MM-dd HH:mm:ss";

    private static ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<>();
    private static ThreadLocal<SimpleDateFormat> dateTimeFormatter = new ThreadLocal<>();
    private static ThreadLocal<SimpleDateFormat> snFormatter = new ThreadLocal<>();

    private static SimpleDateFormat snFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 取得当前时间戳,单位:秒
     * @return
     */
    public static long getTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成[年月日时分秒]格式的字符串
     * @return
     */
    public static String generateSn() {
        SimpleDateFormat format = snFormatter.get();
        if (null == format) {
            format = new SimpleDateFormat("yyyyMMddHHmmss");
            snFormatter.set(format);
        }
        return format.format(new Date());
    }
    /**
     * 格式化输出日期字符串
     * @param date 日期
     * @return 返回对应格式的字符串
     */
    public static String format(Date date) {
        SimpleDateFormat dateFormat = dateFormatter.get();
        if (null == dateFormat) {
            dateFormat = new SimpleDateFormat(dateFormatPattern);
            dateFormatter.set(dateFormat);
        }
        return dateFormat.format(date);
    }

    /**
     * 格式化输出日期时间字符串
     * @param date 日期
     * @return 返回对应格式的字符串
     */
    public static String formatDateTime(Date date) {
        SimpleDateFormat dateFormat = dateTimeFormatter.get();
        if (null == dateFormat) {
            dateFormat = new SimpleDateFormat(dateTimeFormatPattern);
            dateTimeFormatter.set(dateFormat);
        }
        return dateFormat.format(date);
    }
    /**
     * 解释日期时间
     * @param source 日期字符串
     * @return 符合格式返回对应日期,否则返回null
     */
    public static Date parseDate(String source) {
        SimpleDateFormat dateFormat = dateFormatter.get();
        if (null == dateFormat) {
            dateFormat = new SimpleDateFormat(dateFormatPattern);
            dateFormatter.set(dateFormat);
        }
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 解释日期时间
     * @param source 日期时间字符串
     * @return 符合格式返回对应日期,否则返回null
     */
    public static Date parseDateTime(String source) {
        SimpleDateFormat dateFormat = dateTimeFormatter.get();
        if (null == dateFormat) {
            dateFormat = new SimpleDateFormat(dateTimeFormatPattern);
            dateTimeFormatter.set(dateFormat);
        }
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            return null;
        }
    }
}
